import { api } from './api'
import type { ApiResponse, PaginatedResponse, SearchParams } from '../types'

interface SearchResult {
  type: 'ARTICLE' | 'USER' | 'COMMENT'
  id: number
  title: string
  content: string
  highlight: {
    title?: string[]
    content?: string[]
  }
  author: {
    id: number
    username: string
    avatar?: string
  }
  createdAt: string
}

interface SearchSuggestion {
  type: 'ARTICLE' | 'USER' | 'TAG' | 'CATEGORY'
  id: number
  title: string
  description?: string
}

interface SearchStatsResult {
  totalResults: number
  articleResults: number
  userResults: number
  commentResults: number
  processingTime: number
}

export const searchApi = api.injectEndpoints({
  endpoints: (builder) => ({
    search: builder.query<ApiResponse<PaginatedResponse<SearchResult>>, SearchParams>({
      query: (params) => ({
        url: '/search',
        params,
      }),
      providesTags: ['Search'],
    }),

    getSuggestions: builder.query<ApiResponse<SearchSuggestion[]>, string>({
      query: (query) => ({
        url: '/search/suggestions',
        params: { query },
      }),
      providesTags: ['Search'],
    }),

    getSearchStats: builder.query<ApiResponse<SearchStatsResult>, SearchParams>({
      query: (params) => ({
        url: '/search/stats',
        params,
      }),
      providesTags: ['Search'],
    }),

    getPopularSearches: builder.query<ApiResponse<{ query: string; count: number }[]>, number>({
      query: (limit = 10) => ({
        url: '/search/popular',
        params: { limit },
      }),
      providesTags: ['Search'],
    }),

    getRelatedSearches: builder.query<ApiResponse<string[]>, string>({
      query: (query) => ({
        url: '/search/related',
        params: { query },
      }),
      providesTags: ['Search'],
    }),
  }),
})

export const {
  useSearchQuery,
  useGetSuggestionsQuery,
  useGetSearchStatsQuery,
  useGetPopularSearchesQuery,
  useGetRelatedSearchesQuery,
} = searchApi 